package com.zd.commodity.product_pic.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import utils.CopyFileUtil;
import utils.ExcelUtil;
import utils.FileUtility;

import com.alibaba.fastjson.JSONObject;
import com.zd.commodity.action.BaseAction;
import com.zd.commodity.product_pic.biz.IProductPicBiz;
import com.zd.commodity.product_pic.entity.ProductPic;

@Scope("prototype")
@Controller("productPicAction")
public class ProductPicAction extends BaseAction<ProductPic> {

	private IProductPicBiz productPicBiz;

	@Autowired
	public void setProductPicBiz(IProductPicBiz productPicBiz) {
		this.productPicBiz = productPicBiz;
		this.setBaseBiz(productPicBiz);
	}
	
	private String type;
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	
	private File uploadify;
    public File getUploadify() {
		return uploadify;
	}
	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}

	private String uploadifyFileName;
	public String getUploadifyFileName() {
		return uploadifyFileName;
	}

	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}
	
	public String upload() throws Exception{
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setCharacterEncoding("utf-8");
		String path = request.getSession().getServletContext().getRealPath("");       // 项目路径
		
		path = path.substring(0,path.lastIndexOf(File.separator));                    // 项目上一级路径

		String url ="/"+this.getPath("uploads")+"/"+getType()+"/";                  // 图片统一放置在uploads文件夹下---type：文件夹名（建议为功能名）
		
		
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		url += df.format(date);// 文件夹--日期
		url += "/";
		
		
		File f2 = new File(path+url);
		if (!f2.exists()) {
			f2.mkdirs();
		}
		
		
		String name = "";
		String extName = "";
		// 获取扩展名
		if (uploadifyFileName.lastIndexOf(".") >= 0) {
			extName = uploadifyFileName.substring(uploadifyFileName.lastIndexOf("."));
		}
		File file = null;
		String image200px="";
		
		do {
			name = UUID.randomUUID().toString();
			file = new File( path + url + name + extName);
		} while (file.exists());
		CopyFileUtil.copyFile(uploadify.getPath(),file.getPath(), true);   //生成原图
		uploadify.delete();
		
		//生成200px的图
		if(extName.equalsIgnoreCase(".jpg") || extName.equalsIgnoreCase(".png") || 
				extName.equalsIgnoreCase(".gif") || extName.equalsIgnoreCase(".JPEG") || 
				extName.equalsIgnoreCase(".PNG") || extName.equalsIgnoreCase(".GIF")){
			String fileS =path + url + name + extName;
	        int point = fileS.lastIndexOf(".");
	        
			image200px = fileS.substring(0, point) + "new" + extName;//（列表页搜索结果图）

			FileUtility.generateImageThumb(fileS, image200px, 200, 200);     //利用原图截取200px的图
			
		    File f=new File(fileS);  //删除原图片
		    f.delete();
		}
		
		String Path200px=image200px.substring(image200px.indexOf("/"), image200px.length());
		
		response.getWriter().print(Path200px);
		return null; // 这里不需要页面转向，所以返回空就可以了
	}
	
	
	public String getPath(String arg){
		// 配置文件在src下获取配置文件路径
		InputStream path = this.getClass().getClassLoader().getResourceAsStream("sys.properties");// 获取src下的配置文件
		Properties prop = new Properties();
		try {
			prop.load(path);// 加载配置文件
			/*System.out.println(prop.getProperty("ImgUrl"));*/
		} catch(IOException e) {
			e.printStackTrace();
		}
		return prop.getProperty(arg);// 返回配置文件中的某一属性
	}


	/**
	 * 下载模板
	 * @throws Exception 
	 */
	public void downloadTemplet() throws Exception{
		List templet = productPicBiz.getExcelExportListBySql(ProductPic.class, "downloadTemplet", null, 0, 0);
		String[] title = new String[]{"图片名称","上传路径"};
		String[] neededFields = new String[]{"name","path"};
		super.excelExport("图片上传模板", templet,title,neededFields);
	}
	
	/**
	 * 模板导入
	 * @throws Exception 
	 */
	public void uploadExeclData() throws Exception{
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();	
		
		
		String message="上传成功";
		
		HashMap<Integer, String> map = new HashMap<Integer ,String>();
		map.put(1, "notNull");
		List<String[]> data = productPicBiz.readExecl(map);
		
		if(data.size()==1){
			String[] strings = data.get(0);
			if("0".equals(strings[0])){
				message = strings[1];
				out.print(message);
			}
		}
       
		
		if(message.equals("上传成功")){
			List<String> errorMsg=new ArrayList<String>();//存放错误信息
			
			//② 判断名字是否重复     先判断excel中是否有重复的   在判断与数据库中是否重复
			//检验excel上传name是否有重复
			List<String> repeatName = ExcelUtil.ExcelColumRepeats(data, new int[]{0});
			if(repeatName!=null && repeatName.size()>0){
				for (String string : repeatName) {
					errorMsg.add(string);
				}
			}
			//检验数据库中是否已存在
			List<String> repeatBatch = productPicBiz.checkExcelRepeatBatch(data,"checkProductPicExist",new int[]{0});
			
			
			List<ProductPic> productPics=new ArrayList<ProductPic>(); 
			//遍历提交的信息
			for (int i=0;i<data.size();i++) {
				String[] strings=data.get(i);
			
                //① 把服务器中图片的名字改了 然后存放到数据库中      保存的路径要/   通过目录查找的要\
				if(strings[1]==null||strings[1].equals(" ")){
					errorMsg.add("第"+(i+2)+"行的图片路径为空");
					continue;
				}
				
				String realPath = request.getSession().getServletContext().getRealPath(""); // 项目路径
				realPath = realPath.substring(0,realPath.lastIndexOf(File.separator));      // 项目上一级路径
				strings[1]=strings[1].replace("\\", "/");  //路径中如果有\变为/
				
				//完整路径
				String allPath=realPath+strings[1];
				allPath = allPath.replace("/", "\\");
				
				String contentPath = allPath.substring(0, allPath.lastIndexOf("\\")); //目录路径
				File directory = new File(contentPath); 
				File oldFile = new File(allPath); 
				
				//对传入的路径进行拆分
				String filename = strings[1].substring(0, strings[1].lastIndexOf("/"));
				String newName = UUID.randomUUID().toString()+"new";
				String extension = strings[1].substring(strings[1].indexOf(".")+1);
				
				if (directory.isDirectory()) { //判断是不是目录
					if(oldFile.exists()){//判断传进来的图片是否存在 
						 String newAllPath = contentPath + "\\" + newName+"."+extension; 
		                 File newFile = new File(newAllPath);  
		                 if (!newFile.exists()) {  
		                	 oldFile.renameTo(newFile);  //开始更名 
		                 }
					}else{
						errorMsg.add("第"+(i+2)+"行第2列的图片不存在于该目录中");
					}
	
			    }else{
			    	errorMsg.add("第"+(i+2)+"行第2列的目录路径存在错误");
			    }
				String path = filename +"/"+ newName + "." + extension;
				
				ProductPic productPic = new ProductPic();
				productPic.setName(strings[0]);
				productPic.setPath(path);
				productPics.add(productPic);
			}
			
			
			//都成功了再全部添加    有一个不成功就不添加
			if(errorMsg.size()==0 && repeatBatch.size()==0){
				for (ProductPic productPic : productPics) {
					productPicBiz.add(productPic);
				}
				out.write(message);
			}else{
				out.println("以下属性数据库已存在：");
				for (String string : repeatBatch) {
					out.println(string+",");
				}
				
				for (String msg : errorMsg) {
					out.println(msg);
				}
			}
			
		
		}

		out.flush();
		out.close();
	}

	/**
	 * 判断tupian名称在数据库中是否已存在
	 */
	public void nameExist() throws IOException{
		String name=super.getT().getName();
		HashMap<String, String> map=new HashMap<String, String>();
		map.put("tableName","product_pic" );
		map.put("columName","name" );
		map.put("value", name);
		Long  size = productPicBiz.getPagedListCountBySql("queryRepeat", map);
		JSONObject json=new JSONObject();
		
		if(size>0){
			json.put("valid", false);
		}else{
			json.put("valid", true);
		}
		response.getWriter().write(json.toString());
	}
}
